
require("config")
require("framework.init")
require("framework.shortcodes")
require("framework.cc.init")

local GameScene  = class("GameScene", function()
    return display.newScene("GameScene")
end)


local TAG_WORLD       = 1
local TAG_SPBODY      = 11
local TAG_SPBODY2     = 12

function GameScene:ctor()
  local backColor = display.newColorLayer(ccc4(20,5,40,128)):addTo(self)
  local world = CCPhysicsWorld:create(0, -100):addTo(self)
  world:setTag(TAG_WORLD)

 
  local staticBody = CCPhysicsBody:createStaticBody(world)
  staticBody:addSegmentShape(CCPoint(100,20), CCPoint(display.width-100,20), 10)
  staticBody:setFriction(0.4)
  staticBody:setElasticity(0.8)
  staticBody:setPosition(0,20)
  world:addBody(staticBody)                                                       --创建body后，还是要addBody进world
  --local defBody = CCPhysicsBody:defaultStaticBody(world)
  --world:addBody(defBody)

  local sprite = display.newSprite('CloseNormal.png'):addTo(self)
  local spBody = world:createCircleBody(20, 20)
  spBody:bind(sprite)
  spBody:setPosition(display.cx-200,display.cy)
  spBody:setFriction(0.5)
  spBody:setElasticity(0.75)
  spBody:setTag(TAG_SPBODY)
  CCLuaLog(string.format('spBody Inertia = %g',spBody:getInertia()))
  --spBody:setInertia(2000)

  local sprite2 = display.newSprite('CloseNormal.png'):addTo(self)
  local spBody2 = world:createBoxBody(20, 50, 50)
  spBody2:bind(sprite2)
  spBody2:setPosition(display.cx-100,display.cy)
  spBody2:setFriction(0.6)
  spBody2:setElasticity(0.4)
  spBody2:setTag(TAG_SPBODY2)

  spBody:setCollisionType(1)                                                --设置碰撞检测type
  spBody2:setCollisionType(2)                                               
  --world:addCollisionScriptListener(onCollisioned, 1, 2)                     --创建碰撞检测





  CCLuaLog(string.format('world Dauping = %g',world:getDamping()))
  CCLuaLog(string.format('world IdleSpeed = %g',world:getIdleSpeedThreshold()))
  world:setDamping(0.8)
  world:setIdleSpeedThreshold(1)
  world:createDebugNode():addTo(self)
  world:start()

  local touch = display.newLayer():addTo(self)
  touch:setTouchEnabled(true)
  touch:addNodeEventListener(cc.NODE_TOUCH_EVENT, onTouch)

  local item = ui.newImageMenuItem({image='CloseNormal.png',imageSelected='CloseSelected.png',listener=onClicked,tag=1})
  local menu = ui.newMenu({item}):addTo(self)
  menu:pos(display.width-40,display.height-40)

  self:addNodeEventListener(cc.NODE_ENTER_FRAME_EVENT, function (dt) self:onEnterFrame(dt) end)       --帧定时器，用于删除body,sprite
  self:scheduleUpdate()

end

local isV = false
function onClicked(tag)
  CCLuaLog('... onClicked ...')
  --[[
  local sprite = display.getRunningScene():getChildByTag(TAG_WORLD):getBodyByTag(TAG_SPBODY)
  local x,y = 0,0
  local v = sprite:getVelocity()
  CCLuaLog(type(v))
  --CCLuaLog(string.format('sprite Velocity x= %g, y= %g',x,y))
  CCLuaLog(string.format('sprite Velocity = %g',v))
  if not isV then isV = true sprite:setVelocity(CCPoint(100,100)) end
  ]]

  local world = display.getRunningScene():getChildByTag(TAG_WORLD)
  local array = world:getAllBodies()
  printf('world have %d bodys ',array:count())

  return false
end


function onTouch(event)
  CCLuaLog('... onTouch ...')
  --local sprite = display.getRunningScene():getChildByTag(TAG_WORLD):getBodyByTag(TAG_SPBODY)
  --local sprite2 = display.getRunningScene():getChildByTag(TAG_WORLD):getBodyByTag(TAG_SPBODY2)
  --sprite:applyForce(0, 200)
  --sprite:applyImpulse(100, 0)
  --CCLuaLog(string.format('applyForce = %g',sprite:))
  --sprite:applyForce(100, 0)
  --sprite:applyImpulse(200,0)
  --sprite2:applyImpulse(200,0)
  --sprite:applyForce(100, 200)
  local scene = display.getRunningScene()
  local world = scene:getChildByTag(TAG_WORLD)
  local newSprite = display.newSprite('CloseNormal.png'):addTo(scene)
  local ran = math.random(1,2)                                            --随机1或者2，用于创建不同形状的body
  local vx = math.random(50,100)                                          --随机获取速度x,y的分量
  local vy = math.random(100,200)
  local newBody
  if ran == 1 then
    newBody = world:createCircleBody(20, 20)
    newBody:setFriction(0.2)
    newBody:setElasticity(0.8)
  else
    newBody = world:createBoxBody(20, 50, 50)
    newBody:setFriction(0.65)
    newBody:setElasticity(0.4)
  end
  newBody:bind(newSprite)
  newBody:setPosition(event.x,event.y)

  local dic = math.random(-1,2)                                           --随机设置速度分量的方向
  if dic < 0 then vx = -vx end
  dic = math.random(-1,1)
  if dic < 0 then vy = -vy end
  newBody:setVelocity(vx,vy)


  return false
 
end

--[[
eventName = begin,preSolve,postSolve,separate(分开)
CollisionEvent:CCPhysicsCollisionEvent类实例
]]
function onCollisioned(eventName,CollisionEvent)
  if eventName == 'begin' then
    CCLuaLog('... onCollisioned ...')
    CCLuaLog('Collision name = ' .. eventName)
    local s = CollisionEvent:getWorld()
   -- if not s then CCLuaLog('the s is nil!') else CCLuaLog('userData is class CCPhysicsCollisionEvent!') end
    printf('getTag = %d',s:getTag())
  end

  printf('getCount = %d',CollisionEvent:getCount())       --getCount()，获取碰撞的碰撞点数量
  return true                 --return false不做碰撞处理，物体将穿过
end

function GameScene:onEnter()
	CCLuaLog('GameScene:onEnter')																				--启用定时器监听
end


function GameScene:enterScene(sceneName, args, transitionType, time, more)
	 print('GameScene:enterScene..................')
end

function GameScene:onEnterFrame(dt)
  --CCLuaLog('... onEnterFrame ...')
  ---[[
  local world = display.getRunningScene():getChildByTag(TAG_WORLD)
  local array = world:getAllBodies()                                    --获取所有body

  local deleteArray = CCArray:create()
  local count = array:count() - 1                 --CCArray下标从0开始
  local body,sprite
  for index=1,count do                           --第一个(index=0)为地板，不用删除
    body = array:objectAtIndex(index)
    if body:getPositionY() < 40 then
      --array:removeObjectAtIndex(index)
      --CCLuaLog('... add deleteArray ...')
      --sprite = body:getNode()                   --不能在遍历数组时删除里面body
      --sprite:removeSelf()
      --body:removeSelf()
      deleteArray:addObject(body)
    end
  end
  --]]
  ---[[
  --array:removeObjectsInArray(deleteArray)  
  count = deleteArray:count() - 1
  for index=0,count do 
    body = deleteArray:objectAtIndex(index) 
    sprite = body:getNode()                       --获取bind的节点
    sprite:removeSelf()                           --删除节点
    body:removeSelf()                             --删除body
  end
  --]]
end

game = {}

function game.startup()
    CCFileUtils:sharedFileUtils():addSearchPath("res/")
    print('startup..................')
    game.enterMainScene()
end

function game.exit()
    CCDirector:sharedDirector():endToLua()
    print('exit..........')
end

function game.enterMainScene()
	print('GameScene.new',type(GameScene.new))
    display.replaceScene(GameScene.new(), "fade", 0.6, display.COLOR_WHITE)
end
return game